package concurrent.chapter3;

public class VolatileTest2 {
    //没有加volatile关键字，线程会从cpu cache拿数据，但发生修改会刷新回主内存，还是会从主内存中取数据
    //private static int INIT_VALUE = 0;
    //加了volatile不能保证原子性，多线程下会有问题
    //T2 -> [21]
    //T1 -> [21]
    private static volatile int INIT_VALUE = 0;
    private final static int MAX_LIMIT = 50;

    public static void main(String[] args) {
        new Thread(() -> {
            while (INIT_VALUE < MAX_LIMIT) {
                System.out.printf("T1 -> [%d]\n", ++INIT_VALUE);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "ADDER-1").start();
        new Thread(() -> {
            while (INIT_VALUE < MAX_LIMIT) {
                System.out.printf("T2 -> [%d]\n", ++INIT_VALUE);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "ADDER-2").start();

    }
}
